↜ Back to index Introduction to Numerical Analysis 1
Part b—Lecture 8
Report 2 is assigned. Submit the solutions by August 6 (Friday) to LMS.
Allocatable arrays
So far we have been using arrays whose size is determined at the compile time. However, it is possible to set the size during runtime, for example based on users output. This is what Fortran’s allocatable
arrays are for.
implicit none
real, dimension(:), allocatable :: x, y
integer n, i
! we cannot use arrays x, y yet since it is not allocated
print *, 'Enter array size'
read *, n
! allocate the memory for n elements
allocate(x(n))
! allocate the memory for n + 1 elements
allocate(y(0:n))
! now we can start using x as any other array with elements x(1), x(2), ..., x(n)
do i = 1, n
= i
x(i) enddo
print *, x
do i = 0, n
= i
y(i) enddo
print *, y
end
This is how we can modify the code for the heat equation using allocatable arrays.
implicit none
real, parameter :: pi = 4. * atan(1.)
integer n, k, nmax, M
real h, tau, x
real, dimension(:), allocatable :: u, v
read *, M
allocate(u(0:M))
allocate(v(0:M))
= 1. / M
h = h * h / 4.
tau = 0.25 / tau
nmax
do k=0, M
= k * h
x = sin(pi * x)
u(k) end do
call printstep(0., u)
do n=0, nmax-1
0) = u(0) ! boundary condition is constant in time
v(do k = 1, M-1
= u(k) + (tau / (h * h)) * (u(k - 1) - 2 * u(k) + u(k + 1))
v(k) end do
= u(M) ! boundary condition is constant in time
v(M)
call printstep((n+1) * tau, v)
= v
u end do
contains
subroutine printstep(tn, un)
real tn
real, dimension(:), allocatable :: un
integer k
do k = 0, M
print *, tn, k * h, un(k)
end do
print *
end subroutine
end